import Util from "../../utils/util";
/*product_2{
     amount: 1
    bag_price: 1
    id: 2
    limit_num: 3
    min_buy: 1
    price: 15
    product_type: 0

    items: [
        {
          skuTxt: "加香菜",
          amount: 10,
          total_price: "15.0"
          skus: [
            check: true
            id: 2
            price: "0.00"
            title: "加香菜"
          ]
        },
        {
          total_price: "15.0"
          skuTxt: "加香菜",
          amount: 10,
          skus: [
            check: true
            id: 2
            price: "0.00"
            title: "加香菜"
          ]
        }
    ]
}
*/
const app = getApp()
Component({
  properties: {
    currentGoods: {
      type: Object,
      value: {},
      observer: function (newVal, oldVal) {
        if (!Util.isEmpty(newVal)) {
          let carts = Util.getCartList(),
            currentGoods = this.data.currentGoods,
            cartKey = this.data.cartKey;

          let cartList = carts ? (carts[cartKey] || null) : null;
          this.setData({
            cartList: cartList
          })

          this.initData();

          if (!Util.isEmpty(currentGoods) && !Util.isEmpty(cartList) && !Util.isEmpty(cartList['product_' + currentGoods.id])) {
            // 初始化产品
            if (!Util.isEmpty(cartList['product_' + currentGoods.id].skus)) {
              currentGoods.specs.forEach((e1, idx) => {
                e1.items.forEach((e2, idx2) => {
                  cartList['product_' + currentGoods.id].skus.forEach((e3, idx3) => {
                    if (e3.id == e2.id) {
                      e2.check = true;
                      if (e3.cart_amount)
                        e2.cart_amount = e3.cart_amount;
                    }
                  })
                })
              })

              this.setData({
                currentGoods: currentGoods,
                checkSkuTxt: cartList['product_' + currentGoods.id].skuTxt || '',
              })
            }
          }

        }
      }
    },
    bagPrice: {
      type: Number,
      value: 0,
    },
    cartKey: {
      type: String,
      value: '',
      observer: function (newVal, oldVal) {
        if (newVal) {
        }
      }
    },

    cartBottom: {
      type: Number,
      value: 60,
    }
  },

  data: {
    skuDialog: true,
    cartList: [],
    totalPrice: 0,
    showSkuCartBtn: false,
    skus: [],
    currentCart: {}
  },

  attached: function () {
    // this.initData();
  },

  methods: {

    initData() {
      const that = this
      let cartList = Util.getCartList(),
        carts = this.data.cartList,
        currentGoods = this.data.currentGoods;

      if (Util.isEmpty(currentGoods) || Util.isEmpty(carts) || Util.isEmpty(carts['product_' + currentGoods.id]))
        return false;

      let products = carts['product_' + currentGoods.id].items || null;
      if (Util.isEmpty(products))
        return;

      let current_skus = products[products.length - 1].skus || []
      let currentCart = products[products.length - 1];
      this.setData({
        totalPrice: (parseFloat(currentCart.total_price || currentGoods.price || 0) * parseInt(currentCart.amount || 1)).toFixed(1),
        showSkuCartBtn: true
      })

      this.setData({
        currentCart: currentCart,
        checkSkuTxt: currentCart.skuTxt || '',
        checkSkus: current_skus,
      })

      currentGoods.specs.map((e1, k1) => {
        e1.items.map((e2, k2) => {
          current_skus.map((e3, k3) => {
            if (e3.id == e2.id) {
              e2.check = true;
              if (e3.cart_amount)
                e2.cart_amount = e3.cart_amount;
            }
          })
        })
      })

      this.setData({
        currentGoods: currentGoods
      })
    },

    closeLayer(e) { //关闭
      this.triggerEvent("closeSku")
    },

    changeSku(e) { //选择 规格
      const index = e.currentTarget.dataset.index,
        sindex = e.currentTarget.dataset.sindex,
        type = e.currentTarget.dataset.type;

      let product = this.data.currentGoods;
      if (Util.isEmpty(product.specs) || Util.isEmpty(product.specs[index].items)) {
        return false;
      }

      //规格多选
      if (product.specs[index].is_multi == 1) {
        if (type == 1) { //增加
          let selectAmount = 0;
          product.specs[index].items.forEach((item, sidx) => {
            selectAmount += (item.cart_amount || 0);
          })

          if (selectAmount >= product.specs[index].amount) {
            return Util.Tips({title: "超出限购数量" + product.specs[index].amount + '份', hideMask: true})
          }

          product.specs[index].items[sindex].cart_amount = (product.specs[index].items[sindex].cart_amount || 0) + 1;
          product.specs = product.specs;
        } else { //减少
          product.specs[index].items[sindex].cart_amount -= 1;
          if (product.specs[index].items[sindex].cart_amount <= 0) {
            product.specs[index].items[sindex].cart_amount = 0;
          }
        }

        if (product.specs[index].items[sindex].cart_amount > 0) {
          product.specs[index].items[sindex].check = true;
        } else {
          product.specs[index].items[sindex].check = false;
        }
      } else {
        product.specs[index].items.forEach((item, sidx) => {

          if (product.product_type == 1) {
            if (product.specs[index].amount == 1) {
              if (item.check && sidx != sindex) {
                item.check = false;
              }
            }
            if (sidx == sindex) {
              item.check = !item.check;
            }
          } else if (sidx === sindex) {
            item.check = !item.check;
          } else {
            if (!item.muti) {
              item.check = false;
              return;
            }
          }
        })
      }

      //判断数量
      let select_amount = 0;
      product.specs[index].items.map(item => {
        if (item.check) {
          select_amount += 1;
        }
      })

      if (select_amount > product.specs[index].amount) {
        Util.Tips({
          title: product.specs[index].title + '最多选择' + product.specs[index].amount + '份',
          hideMask: true
        })
        product.specs[index].items[sindex].check = false;
        return;
      }

      //检查是否显示按钮
      let showSkuCartBtn = true,
        checkSkuTxt = [],
        checkSkus = [],
        currentCart = {},
        totalPrice = parseFloat(product.price || 0);

      if (product.product_type == 1) { //套餐

        product.specs.map(spec => {
          let sTotal = 0;
          spec.items.map(item => {
            if (product.product_type == 1) {

              if (item.check) {
                sTotal += parseInt(item.cart_amount || item.amount);
                checkSkuTxt.push(item.title + 'x' + (item.cart_amount || 1));
                checkSkus.push(item);
                totalPrice += parseFloat(item.price || 0); // 计算价格
              }
            }
          })

          if (spec.amount > sTotal) {
            showSkuCartBtn = false;
            return;
          }

          if ((spec.amount <= spec.items.length && sTotal < spec.amount)) {
            showSkuCartBtn = false;
            return;
          }
        })
      } else { //多规格
        for (const k in product.specs) {
          let spec = product.specs[k];
          let sTotal = 0;
          spec.items.map(item => {
            if (item.check) {
              sTotal += 1
              checkSkuTxt.push(item.title);
              checkSkus.push(item);
              totalPrice += parseFloat(item.price || 0); // 计算价格
            }
          })

          if (sTotal == 0 || (spec.amount <= spec.items.length && sTotal < spec.amount)) {
            showSkuCartBtn = false;
          }
        }
      }

      this.setData({
        showSkuCartBtn: showSkuCartBtn,
        currentGoods: product,
      })

      let cartList = this.data.cartList;
      if (!Util.isEmpty(cartList) && !Util.isEmpty(cartList['product_' + product.id])) {

        let carts = Util.getCartList() || {},
          cartKey = this.data.cartKey;

        if (checkSkus.length > 0) {
          currentCart = {
            skus: checkSkus,
            id: product.id,
            total_price: totalPrice.toFixed(1),
            skuTxt: checkSkuTxt.join(",")
          };

          //判断是否已经存在
          let cartProduct = cartList['product_' + product.id];
          if (Util.isEmpty(cartProduct.items)) {
            cartProduct.items = [];
            cartProduct.items.push(currentCart);
          } else {
            let check_skuIds = [];
            checkSkus.map(e1 => {
              check_skuIds.push(e1.id);
            })
            check_skuIds.sort((a, b) => a - b);

            cartProduct.items.map((e1, k1) => {
              let cp_skuIds = e1.skuId_txt.split("-").sort((a, b) => a - b);
              if (check_skuIds.join("-") === cp_skuIds.join("-")) {
                currentCart.amount = e1.amount;
                totalPrice = parseFloat(e1.total_price) * parseInt(e1.amount)
                return;
              }
            })
          }

          cartList['product_' + product.id] = cartProduct;
          carts[cartKey] = cartList;
          carts[cartKey] = cartList;
        } else {
          delete cartList['product_' + product.id];
          delete carts[cartKey]['product_' + product.id];
        }
        this.setData({
          cartList: cartList
        })
        if (Util.isEmpty(carts[cartKey])) {
          delete carts[cartKey];
        }

        wx.setStorageSync("carts", JSON.stringify(carts))
        this.triggerEvent("confirmAddCart");
      } else {
        currentCart = {
          skus: checkSkus,
          id: product.id,
          total_price: totalPrice.toFixed(1),
          skuTxt: checkSkuTxt.join(",")
        };
      }

      this.setData({
        checkSkus: checkSkus,
        currentCart: currentCart, //当前购物车
        checkSkuTxt: checkSkuTxt.join(','),
        showPrice: checkSkuTxt.length > 0 ? true : false, //显示价格
        showSkuCartBtn: showSkuCartBtn,
        totalPrice: totalPrice.toFixed(1)
      })
      // this.initData();
    },

    addSkuCart(e) { //增加规格到购物车
      const that = this,
        checkSkus = that.data.checkSkus,
        type = parseInt(e.currentTarget.dataset.type);  // 1 : 增加  0： 减少

      let product = this.data.currentGoods || null;
      if (Util.isEmpty(product)) {
        return;
      }
      const cartKey = this.data.cartKey || null;
      let cartList = Util.getCartList() || {},
        amount = 0,
        currentCart = this.data.currentCart || {},
        carts = {};

      if (!Util.isEmpty(cartList) && !Util.isEmpty(cartList[cartKey])) {
        carts = cartList[cartKey]
      }

      //判断是否新新增
      if (Util.isEmpty(carts) || Util.isEmpty(carts['product_' + product.id])) {//新增
        if (type === 1) {
          carts['product_' + product.id] = {
            title: product.title,
            id: product.id,
            amount: 0,
            thumb: product.thumb,
            price: product.price || 0.00,
            bag_price: product.bag_price || 0,
            limit_num: product.limit_num || 0,
            min_buy: product.min_buy || 0,
            product_type: product.product_type || 0
          }
        }
      } else {
        amount = this.data.currentCart.amount || 0;
      }

      if (type === 1) {
        if (product.min_buy > 0) {
          amount += product.min_buy;
        } else {
          amount += 1;
        }
      } else {
        if (product.min_buy > 0 && product.min_buy >= amount) {
          amount -= product.min_buy || 0;
        } else {
          amount -= 1;
        }
      }

      if (product.limit_num > 0 && amount > product.limit_num) {
        return Util.Tips({title: "限购数量" + product.limit_num + '份', hideMask: true})
      }

      amount = amount <= 0 ? 0 : amount;
      if (amount === 0) {
        let skuTxt = [],
          skuIds = [];

        checkSkus.map((e1) => {
          skuIds.push(e1.id);
        })
        currentCart.amount = 0;
        currentCart.skuId_txt = (skuIds.sort()).join("-");
        carts['product_' + product.id].items.map((e1, k1) => {
          if (Util.isEmpty(e1) || Util.isEmpty(e1.skuId_txt)) return;
          if (e1.skuId_txt == currentCart.skuId_txt) {
            carts['product_' + product.id].items.splice(k1, 1);

            if (Util.isEmpty(carts['product_' + product.id].items)) {
              delete carts['product_' + product.id];
            }
          }
        })

      } else {
        if (!Util.isEmpty(checkSkus)) {
          let skuTxt = [],
            skuIds = [],
            totalPrice = parseFloat(product.price);

          checkSkus.map((e1) => {
            skuIds.push(e1.id);
            if (product.product_type == 1) {
              skuTxt.push(e1.title + ' x' + (e1.cart_amount || 1));
            } else {
              skuTxt.push(e1.title);
            }

            if (e1.price > 0) {
              totalPrice += parseFloat(e1.price);
            }
          })
          currentCart.skuId_txt = (skuIds.sort()).join("-");
          currentCart.amount = amount;
          /*          console.log("--------------------------------")
                    console.log(carts)
                    console.log("carts --------------------------------")*/
          if (skuTxt.length > 0) {
            if (Util.isEmpty(carts['product_' + product.id])) {
              carts['product_' + product.id] = {
                title: product.title,
                id: product.id,
                amount: amount,
                thumb: product.thumb,
                bag_price: product.bag_price || 0,
                limit_num: product.limit_num || 0,
                min_buy: product.min_buy || 0,
                spec_type: product.spec_type || 0,
                product_type: product.product_type || 0,
                is_single_seller: product.is_single_seller || 0,
                items: [currentCart],
              }
            } else {
              if (Util.isEmpty(carts['product_' + product.id].items)) {
                carts['product_' + product.id].items = []
              }

              carts['product_' + product.id].items.map((e1, k1) => {
                if (Util.isEmpty(e1) || Util.isEmpty(e1.skuId_txt)) return;
                if (e1.skuId_txt == currentCart.skuId_txt) {
                  console.log(e1.skuId_txt + '----' + currentCart.skuId_txt);
                  carts['product_' + product.id].items.splice(k1, 1);
                }
              })
              if (amount > 0) {
                carts['product_' + product.id].items.push(currentCart);
              }
            }
          }
        }
      }

      if (!Util.isEmpty(carts['product_' + product.id])) {
        let total_amount = 0;
        carts['product_' + product.id].items.map((e1, k1) => {
          total_amount += parseInt(e1.amount || 0)
        })
        carts['product_' + product.id].amount = total_amount
      }

      that.setData({
        cartList: carts,
        currentCart: currentCart,
        // checkSkus: [],
        // checkSkusTxt: "",
        totalPrice: ((currentCart.total_price || 0) * parseInt(currentCart.amount || 1)).toFixed(1)
      })
      cartList[cartKey] = carts;

      wx.setStorageSync("carts", JSON.stringify(cartList))
      this.triggerEvent("confirmAddCart");
    },

    clearCartDialog(e) { //清空

      this.setData({
        cartList: null,
        cartDialog: false
      })

      wx.removeStorageSync("carts")
      this.triggerEvent("clearCart")
    },

  }
});